package org.javaforever.cookieshop.dao;

import java.util.List;
import org.javaforever.cookieshop.domain.UserBean;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import jakarta.transaction.Transactional;
public interface UserDao extends JpaRepository<UserBean, Long>{
	@Query("from UserBean u")
	public List<UserBean> listAllUsers() throws Exception;

	@Modifying
	@Query("delete from UserBean u where u.id = :id")
	@Transactional
	public void deleteUser(Long id) throws Exception;

	@Modifying
	@Query("update UserBean u set u.active = false where u.id = :id")
	@Transactional
	public void softDeleteUser(Long id) throws Exception;

	@Query("from UserBean u where u.id = :id")
	public UserBean findUserById(Long id) throws Exception;

	@Query("from UserBean u where u.userName = :userName")
	public UserBean findUserByUserName(String userName) throws Exception;

	@Query("from UserBean u where u.active = true")
	public List<UserBean> listActiveUsers() throws Exception;

	@Modifying
	@Query("update UserBean u set u.active = not u.active where u.id = :id")
	@Transactional
	public void toggleUser(Long id) throws Exception;

	@Modifying
	@Query("update UserBean u set u.active = true where u.id = :id")
	@Transactional
	public void activateUser(Long id) throws Exception;

	@Query("from UserBean u where u.id = :id")
	public UserBean findUserFullInfoById(Long id) throws Exception;

	@Query("from UserBean u where u.userName like CONCAT(:shortName, '%')")
	public List<UserBean> searchUserIndexedNamesByShortName(String shortName) throws Exception;

	@Query("select u.salt from UserBean u where u.userName = :userName")
	public String getSaltUser(String userName) throws Exception;

	@Query("select u.password from UserBean u where u.userName = :userName")
	public String getPasswordUser(String userName) throws Exception;

	public Integer countUserByUserName(String userName) throws Exception;

	@Query("select count(*) as countNum from UserBean u where u.active = true")
	public Integer countActiveUserRecords() throws Exception;

	@Modifying
	@Query(value="insert into cs_user_role ( user_id,role_id) values (:userId,:roleId)", nativeQuery=true)
	@Transactional
	public Integer assignRoleToUser(Long userId,Long roleId) throws Exception;

	@Modifying
	@Query(value="delete from cs_user_role  where user_id = :userId and role_id = :roleId", nativeQuery=true)
	@Transactional
	public Integer revokeRoleFromUser(Long userId,Long roleId) throws Exception;

}
